/**
 * 
 */
package org.mspring.mlog.web.module.admin.spider;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.mspring.mlog.api.spider.Spider;
import org.mspring.mlog.api.spider.crawler.DefaultCrawler;
import org.mspring.mlog.api.spider.entity.SpiderRule;
import org.mspring.mlog.api.spider.handler.impl.ContentImageHandler;
import org.mspring.mlog.api.spider.service.PublishRuleService;
import org.mspring.mlog.api.spider.service.SpiderPostService;
import org.mspring.mlog.api.spider.service.SpiderRuleService;
import org.mspring.mlog.api.spider.utils.DocumentUtils;
import org.mspring.mlog.support.log.Log;
import org.mspring.mlog.web.query.SpiderRuleQueryCriterion;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.Sort;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.SessionUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Gao Youbo
 * @since 1994-4-14
 * @Description
 * @TODO
 */
@Widget
@RequestMapping("/admin/spider/rule")
public class Admin_SpiderRuleWidget extends Spider_AbstractWidget {
    @Autowired
    private SpiderRuleService spiderRuleService;
    @Autowired
    private SpiderPostService spiderPostService;
    @Autowired
    private PublishRuleService publishRuleService;

    @SuppressWarnings("rawtypes")
    @RequestMapping("/list")
    @Log
    public String list(@ModelAttribute Page<SpiderRule> rulePage, @ModelAttribute SpiderRule spiderRule, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (rulePage == null) {
            rulePage = new Page<SpiderRule>();
        }
        if (rulePage.getSort() == null) {
            rulePage.setSort(new Sort("id", Sort.DESC));
        }
        rulePage = spiderRuleService.listPage(new SpiderRuleQueryCriterion(queryParams), rulePage);
        model.addAttribute("rulePage", rulePage);
        return "/admin/spider/rule/listRule";
    }

    @RequestMapping("/create")
    public String create_view(@ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        return "/admin/spider/rule/createRule";
    }

    @RequestMapping("/create/save")
    @Log
    public String create_save(@ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        spiderRuleService.createRule(spiderRule);
        return prompt(model, "系统提示", "规则创建成功", "/admin/spider/rule/list");
    }

    @RequestMapping("/edit")
    public String edit_view(@RequestParam(required = false) Long id, @ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id == null) {
            id = SessionUtils.getAttrAsLong(request, "SpiderRuleWidget_edit_id");
        }
        if (id == null) {
            return prompt(model, "请先选择要修改的规则");
        }

        spiderRule = spiderRuleService.get(id);
        if (spiderRule == null) {
            return prompt(model, "请先选择要修改的规则");
        }
        model.addAttribute("spiderRule", spiderRule);
        SessionUtils.setAttr(request, "SpiderRuleWidget_edit_id", id);
        return "/admin/spider/rule/editRule";
    }

    @RequestMapping("/edit/save")
    @Log
    public String edit_save(@RequestParam(required = false) Long id, @ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        spiderRuleService.update(spiderRule);
        return prompt(model, "系统提示", "规则修改成功", "/admin/spider/rule/list");
    }

    @RequestMapping("/delete")
    @Log
    public String delete(@RequestParam(required = false) Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id == null) {
            return prompt(model, "无法判断要删除的项");
        }
        Integer count = publishRuleService.countByRule(id);
        if (count != null && count > 0) {
            return prompt(model, "无法删除正在使用中的采集规则，如要删除请先删除对应的PublisRule");
        }
        spiderRuleService.remove(id);
        return "redirect:/admin/spider/rule/list";
    }

    /**
     * 测试采集URL列表
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/test/urllist")
    @ResponseBody
    public ResponseEntity test_urlList(HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        try {
            String testListURL = RequestUtils.getRequestParameterAsString(request, "testListURL");
            String listRule = RequestUtils.getRequestParameterAsString(request, "listRule");

            SpiderRule rule = new SpiderRule();
            rule.setListRule(listRule);

            Spider spider = new Spider(new DefaultCrawler());

            Document doc = DocumentUtils.getDocument(testListURL);
            List<String> urls = spider.getUrls(doc, rule);

            rsp.setSuccess(true);
            rsp.put("urls", urls);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    /**
     * 测试正文内容
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/test/content")
    @ResponseBody
    public ResponseEntity test_content(HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        try {
            String testContentURL = RequestUtils.getRequestParameterAsString(request, "testContentURL");
            String titleRule = RequestUtils.getRequestParameterAsString(request, "titleRule");
            String contentRule = RequestUtils.getRequestParameterAsString(request, "contentRule");

            SpiderRule rule = new SpiderRule();
            rule.setTitleRule(titleRule);
            rule.setContentRule(contentRule);

            Spider spider = new Spider(new DefaultCrawler());
            spider.addContentHandler("imageHandler", new ContentImageHandler());

            Document doc = DocumentUtils.getDocument(testContentURL);

            Element title = spider.getTitle(doc, rule);
            Element content = spider.getContent(doc, rule);

            if (title != null) {
                rsp.put("title", title.text());
            }
            if (content != null) {
                rsp.put("content", content.children().outerHtml());
            }
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    // @RequestMapping("/run_view")
    // public String run_view(@RequestParam(required = false) Long id,
    // HttpServletRequest request, HttpServletResponse response, Model model) {
    // if (id == null) {
    // id = SessionUtils.getAttrAsLong(request, "SpiderRuleWidget_run_view_id");
    // }
    // if (id == null) {
    // return prompt(model, "请选择要运行的规则");
    // }
    // SpiderRule spiderRule = spiderRuleService.get(id);
    //
    // if (!spiderRule.getEnabled()) {
    // return prompt(model, "该规则已被禁用");
    // }
    //
    // model.addAttribute("spiderRule", spiderRule);
    // SessionUtils.setAttr(request, "SpiderRuleWidget_run_view_id", id);
    // return "/admin/spider/rule/run";
    // }
    //
    // @RequestMapping("/run")
    // public void run(@RequestParam(required = false) Long id,
    // HttpServletRequest request, HttpServletResponse response, Model model) {
    // if (id == null) {
    // PushMessage.push("请选择要运行的规则");
    // return;
    // }
    // SpiderRule spiderRule = spiderRuleService.get(id);
    //
    // if (!spiderRule.getEnabled()) {
    // PushMessage.push("<font style='color:red;'><b>该规则已被禁用</b></font>");
    // return;
    // }
    //
    // Spider spider = new Spider(new DefaultCrawler());
    // spider.addContentHandler("contentImage", new ContentImageHandler());
    //
    // PushMessage.push("开始...");
    // PushMessage.push("开始获取列表：" + spiderRule.getUrl());
    //
    // Document listPageDoc = DocumentUtils.getDocument(spiderRule.getUrl());
    // List<String> urls = spider.getUrls(listPageDoc, spiderRule);
    //
    // Document contentDoc = null;
    // SpiderPost spiderPost = null;
    // for (String url : urls) {
    // if (StringUtils.isNotBlank(url)) {
    // PushMessage.push("分析网址：" + url);
    //
    // Element title = null;
    // Element content = null;
    //
    // try {
    // contentDoc = DocumentUtils.getDocument(url);
    // title = spider.getTitle(contentDoc, spiderRule);
    // content = spider.getContent(contentDoc, spiderRule);
    // } catch (Exception e) {
    // // TODO: handle exception
    // PushMessage.push("<font style='color:red;'>抓取文章失败</font>");
    // PushMessage.push("<font style='color:green;'>******************************************************************************************************************************************************</font><br/>");
    // continue;
    // }
    //
    // if (title == null || content == null) {
    // PushMessage.push("<font style='color:red;'>抓取文章失败</font>");
    // PushMessage.push("<font style='color:green;'>******************************************************************************************************************************************************</font><br/>");
    // continue;
    // }
    //
    // PushMessage.push("文章：" + title);
    // try {
    // spiderPost = new SpiderPost();
    // spiderPost.setSpiderRule(id);
    // spiderPost.setTitle(title.text());
    // spiderPost.setContent(content.html());
    // spiderPostService.createSpiderPost(spiderPost);
    //
    // PushMessage.push("<font style='color:green;'>导入成功</font>");
    // } catch (Exception e) {
    // // TODO: handle exception
    // PushMessage.push("<font style='color:red;'>导入失败</font>");
    // PushMessage.push("<font style='color:green;'>******************************************************************************************************************************************************</font><br/>");
    // continue;
    // }
    //
    // PushMessage.push("<font style='color:green;'>******************************************************************************************************************************************************</font><br/>");
    // }
    // }
    // PushMessage.push("<font style='color:blue;'>全部执行完成。</font><br/>");
    // }
}
